package com.yongjie.springbootlogin.controller;


import com.yongjie.springbootlogin.entity.Adminmuser;
import com.yongjie.springbootlogin.service.Interface.AdminService;
import com.yongjie.springbootlogin.service.LoginService;
import com.yongjie.springbootlogin.utils.ResultMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * 管理员管理
 */
@Controller
public class AdminController {
    @Autowired
    AdminService adminService;
    @Autowired
    private LoginService userLoginService;
    /**
     * 管理员页面
     */
    @RequestMapping(value = "/adminpage")
    public String adminpage (Map<String,Object>map){
        return "adminpage/Addadmin";
    }

    /**
     * 添加管理员
     */
    @RequestMapping("/addAdmin")
    @ResponseBody
    public ResultMessage addAdmin(Adminmuser adminmuser){
        ResultMessage resultMessage=null;
        //判断账号是否存在
        Boolean b = userLoginService.finusernameByusername(adminmuser.getUsername());
        if (b) {
            int count = adminService.addAndmin(adminmuser);
            if (count > 0) {
                resultMessage = new ResultMessage(200, "添加成功");
            } else {
                resultMessage = new ResultMessage(500, "添加失败");
            }
        }else{
            resultMessage = new ResultMessage(400, "用户名已存在！");
        }
        return resultMessage;
    }


    /**
     * 分页
     * @return
     */
    @RequestMapping(value = "/adminLict")
    public String allList(Map<String,Object>map,
                          HttpServletRequest request
    ){
        //获取数据总条数
        Integer count=adminService.AdminCount();
        map.put("count",count);
        String cupage=request.getParameter("currentPage");
        int currentPage;//默认当前页码为1
        int pageSize=5;//每页5条数据
        //计算总页数;
        int pages=(count+pageSize-1)/pageSize;
        //获取当前页码
        currentPage=(cupage==null)?1:Integer.parseInt(cupage);
        //如果当前页码小于1，则赋值为1，表示为首页
        if(currentPage<1) {
            currentPage=1;
        }
        //如果当前页数大于总页数，则赋值为总页数值，表示为尾页
        if(currentPage>pages) {
            currentPage=pages;
        }
        //将当前的页码保存在map中
        map.put("currentPage", currentPage);
        map.put("pages", pages);
        currentPage= (currentPage-1)*pageSize;
        if(currentPage<=0){
            currentPage=0;
        }
        //准备分页的数据
        List<Adminmuser> adminmusers= adminService.getAndminPages(currentPage, pageSize);
        map.put("adminmusers",adminmusers);
        return "adminpage/AdminLict";
    }



}
